# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 生成users集合测试数据.py
# @Author: dongguangwen
# @Date  : 2025-06-14 18:02
from pymongo import MongoClient
from datetime import datetime, timedelta
import random
import bson.binary  # 依赖与pymongo库

# 连接到本地MongoDB（默认端口27017）
client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')

# 创建数据库和集合
db = client['learning_mongodb']
collection = db['users']

# 清空集合（方便重复测试）
collection.delete_many({})


# 模拟数据生成函数
def generate_user(i):
    return {
        "name": f"User_{i}",
        "age": random.randint(18, 65),
        "height": round(random.uniform(1.5, 2.0), 2),
        "is_active": random.choice([True, False]),
        "created_at": datetime.now() - timedelta(days=random.randint(1, 365)),
        "tags": random.sample(["sports", "music", "reading", "coding", "travel"], k=random.randint(1, 3)),
        "address": {
            "city": random.choice(["Beijing", "Shanghai", "Guangzhou", "Shenzhen"]),
            "street": f"{random.randint(100, 999)} Main St",
            "zipcode": str(random.randint(100000, 999999))
        },
        "scores": [round(random.uniform(60, 100), 1) for _ in range(5)],
        "last_login": random.choice([
            None,
            datetime.now() - timedelta(hours=random.randint(1, 48))
        ]),
        "profile_image": bson.binary.Binary(b"fake_binary_data_of_profile_image") if random.random() > 0.3 else None
    }


# 生成并插入10条用户数据
users = [generate_user(i+1) for i in range(10)]
result = collection.insert_many(users)
print(f"成功插入 {len(result.inserted_ids)} 条记录")
